﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using TVWeb.Models;

namespace TVWeb.Controllers
{
    [HandleError]
	public class HomeController : Controller
	{
        CommentRepository m_rep = null;

        public HomeController()
        {
            m_rep = new CommentRepository();
        }
		public ActionResult Index( )
		{
            return View();
		}

		[HttpPost]
		public ActionResult Create( FormCollection formData )
		{
			String strComment = formData[0];
			if ( !String.IsNullOrEmpty( strComment ) )
			{
				Comment c = new Comment( );

				c.CommentText = strComment;
				String strUser = System.Security.Principal.WindowsIdentity.GetCurrent( ).Name;
				if ( !String.IsNullOrEmpty( strUser ) )
				{
					int slashPos = strUser.IndexOf( "\\" );
					if ( slashPos != -1 )
					{
						strUser = strUser.Substring( slashPos + 1 );
					}
					c.UserName = strUser;

					m_rep.AddComment( c );
				}
				else
				{
					c.UserName = "Unknown user";
				}
			//	return RedirectToAction( "Index" );
                return Json(c, JsonRequestBehavior.AllowGet);
            }
			else
			{
				ModelState.AddModelError( "CommentText", "Kjánaprik. Ætlarðu að setja inn tóma athugasemd?" );
				return View();
			}
		}


        public ActionResult Comments()
        {
            var model = m_rep.GetComments();
            var newResult = from c in model
                            select new { CommentDate = c.CommentDate.ToString(), ID = c.ID, CommentText = c.CommentText, UserName = c.UserName };
            return Json(newResult, JsonRequestBehavior.AllowGet);
        }


		public ActionResult About( )
		{
			return View( );
		}

        [HttpPost]
        public ActionResult Save(int? id)
        {
            //útfæra hvaða upplýsingar við geymum

            if( id.HasValue){
                
                var likeUsers = m_rep.GetAllLikes(id.Value);

                    var alreadyLiked = (from like in likeUsers
                                        where like.UserName == System.Security.Principal.WindowsIdentity.GetCurrent().Name
                                        where like.CommentID == id.Value
                                        select like).SingleOrDefault();

                if (alreadyLiked == null)
                {
                    m_rep.AddLike(new Like { CommentID = id.Value, UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name });
                }
 


                // skilum nafni á notendum sem læka kommentið
                var returnValue = from like in likeUsers
                                    select new { User = like.UserName };

                return Json(returnValue);
            }

            return Json("");

        }

	}
}
